package com.changgou.order.config;

import com.alibaba.fastjson.JSON;
import com.changgou.order.service.OrderService;
import com.netflix.discovery.converters.Auto;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/*****
 * @Author: 黑马训练营
 * @Description: com.changgou.order.config
 ****/
@Configuration
@RabbitListener(queues = {"${mq.pay.queue.order}"})
public class OrderPayMessageListener {

    @Autowired
    private OrderService orderService;

    /****
     * 读取消息
     */
    @RabbitHandler
    public void getOrderMessage(String message){
        System.out.println("读取到的消息是："+message);


        //将json字符串转成Map
        Map<String,String> resultMap = JSON.parseObject(message,Map.class);
        /****
         * 获取消息
         * 1.判断用户支付状态
         * 2.支付成功则修改订单状态
         * 3.支付失败，则删除订单
         */
        //通信标识 return_code=SUCCESS
        String returncode = resultMap.get("return_code");
        if(returncode.equals("SUCCESS")){
            //业务标识 result_code=SUCCESS
            String resultcode = resultMap.get("result_code");

            //获取订单号out_trade_no
            String out_trade_no = resultMap.get("out_trade_no");

            //支付成功
            if(resultcode.equals("SUCCESS")){
                //微信支付交易流水号
                String transaction_id = resultMap.get("transaction_id");
                orderService.updateStatus(out_trade_no,transaction_id);
            }else{
                //支付失败
                orderService.deleteOrder(out_trade_no);
            }
        }
    }
}
